package com.itouch.util;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import android.os.Environment;
import android.os.StatFs;

/**
 * cocoaSJ
 */
public class CoFileUtil {

    public static String getMB(Long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        if (returnValue > 1)
            return (returnValue + "  MB ");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return (returnValue + "  KB ");
    }

    /**
     * 判断是否有sd卡
     *
     * @return
     */
    public static boolean haveSDCard() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        return sdCardExist;
    }

    /**
     * 获取sd卡的剩余容量
     *
     * @return
     */
    public static long getSDFreeSize() {
        // 取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        // 获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        // 空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        // 返回SD卡空闲大小
        // return freeBlocks * blockSize; //单位Byte
        // return (freeBlocks * blockSize)/1024; //单位KB
        return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
    }

    /**
     * 创建路径
     *
     * @param path
     * @return
     */
    public static void createPath(String path) {
        File file = new File(path);
        file.mkdirs();

    }

    public static File createFile(String filePathString, String filename) {
        File file = new File(filePathString);
        File finalFile = new File(filePathString + "/" + filename);
        if (!file.exists()) {
            createPath(filePathString);
        }
        try {
            finalFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return finalFile;
    }

    public void createFile(File file) {
        if (file.isFile()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
